package com.kuang.lock;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @program: juc
 * @description:
 * @author: 陈恩涛
 * @create: 2021-03-29 14:58
 **/
public class SpinlockTest {
    public static void main(String[] args) throws InterruptedException {

        SpinlockDemo lock = new SpinlockDemo();

        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                Runtime.getRuntime().availableProcessors(),
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                namedThreadFactory,
                new ThreadPoolExecutor.AbortPolicy()
        );

        threadPoolExecutor.execute(() -> {
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.myUnlock();
            }
        });

        TimeUnit.SECONDS.sleep(1);

        threadPoolExecutor.execute(() -> {
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.myUnlock();
            }
        });
    }
}
